//
//  KLSGCategoryTool.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGCategoryTool.h"

@implementation KLSGCategoryTool

- (void)setupDataWithUrl:(NSString *)urlStr block:(void (^)(NSDictionary *))block failDownloadWithBlock:(void(^)())failBlock
{
    
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url ];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error != nil) {
            // 加载失败，回调
            dispatch_async(dispatch_get_main_queue(), ^{
                failBlock();
            });
            return ;
        }
        NSError *jsonError = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:&jsonError];
        if (jsonError == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(dic);
            });
        }
    }];
    
    [task resume];
}

@end
